<?php
namespace Home\Controller;

use Think\Controller;

/**
 * 店铺控制器
 */
class ShopsController extends CommonController
{
  protected $this_table="shops";
  protected $current_user;

  public function __construct()
  {
    parent::__construct();
    $this->current_user = $this->check_login();
  }

  /**
   * [新建商户]
   * @return [type] [description]
   */
  public function create()
  {
    $img_url = get_shop_wxacode($result, $this->app_id);
    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    //验证合法性
    $data['name'] = trim($data['name']);
    if (!$data['name']) {
      return_data("error", "shop.name.blank");
    }

    //手机验证
    if (!preg_match("/^[+]?[0-9]{1,15}$/", $data['phone'])) {
      return_data("error", "shop.phone.invalid");
    }

    //店名
    $shop_id = M('shops')->where("name='{$data[name]}' or phone='{$data[phone]}' and app_id={$this->app_id}")->getField("id");
    if ($shop_id) {
      return_data("error", "shop.name.or.phone.exist");
    }

    $data["created_at"] = $data["updated_at"] = $this->current_time;
    $data['status'] = 2; //不可用
    $data['descrip'] = '';
    $data['types'] = 2;
    $data['delivery_types'] = 2;
    $current_user = $this->current_user;
    $data['xcx_openid'] = $current_user['xcx_openid'];
    $data['app_id'] = $this->app_id;

    $model = M('shops');
    $model->create($data);
    $result = $model->add();

    if ($result) {
      // $catdata['shop_id'] = $result;
      // $catdata['created_at'] = $catdata['updated_at'] = $this->current_time;
      // $catdata['name'] = '默认分类';
      // M('product_cates')->create($catdata);
      // M('product_cates')->add();

      $app_info = $this->app_info;
      if ($app_info['audit_types'] == 2) {
        $data = array('status' => 1);
        $img_url = get_shop_wxacode($result, $this->app_id);
        if ($img_url) $data['qrcode'] = $img_url;
        M('shops')->where("id=$result")->save($data);
        $shop = M('shops')->where("id=$result")->find();
        return_data('success', 'create.shop.success', $shop);
      } else {
        return_data('success', 'create.shop.success');
      }
    } else {
      return_data('error', 'create.shop.error');
    }
  }

  /**
   * [查看店铺]
   * @return [type] [description]
   */
  public function show()
  {
    $model = M($this->this_table);
    // if(!$this->shop_id) return_data("error",$this->this_table.".id.blank");
    $id = trim(I('id'));

    $where['id'] = trim(I('id'));
    $where['status'] = 1;
    $where['app_id'] = $this->app_id;
    // $where['user_id'] = $this->user_id;
    $field = "id,name,status,phone,addr,lng,lat,open_time,descrip,logo, kfphone, delivery_free, print_code,announcement, print_secret, print_num, qrcode, types, delivery_types, delivery_amount, start_delivery_amount, alipay_account, alipay_name, wxpay_account, amount, unbilled_amount, brokerage, wechat, layout, rate, is_threshold, threshold_rebate, threshold";
    $info = $model->field($field)->where($where)->find();
    // if(empty($info) && $where['id']){
    //   return_data("error", "shop_id.close.blank");
    // }

    $info['descrip'] = mb_substr($info['descrip'], 0, 25, 'UTF8');
    $info['announcement'] = mb_substr($info['announcement'], 0, 40, 'UTF8');
    if (I('is_withdraw')) {
      $info['withdraw_total'] = M('amount_logs')->where("status in (2,3) and shop_id={$id}")->sum("total_amount");
      !$info['withdraw_total'] && $info['withdraw_total'] = 0;
    }

    if (empty($info)) {
      return_data("error", "show.".$this->this_table.".empty");//blank
    } else {
      $history_update = array(
        'shop_id' => $id,
        'user_id' => $this->user_id,
        'updated_at' => $this->current_time
      );

      if($where['id']){
        $history_check = M('history_logs')->where("shop_id=$id and user_id={$this->user_id}")->find();
        if (!$history_check) {
          M('history_logs')->add($history_update);
        } else {
          M('history_logs')->where("shop_id=$id and user_id={$this->user_id}")->save($history_update);
        }
      }
      return_data("success", "show.".$this->this_table.".success", $info);
    }
  }

  /**
  * [查看店铺是否有效]
  * @return [type] [description]
  */
  public function check_shop()
  {
    $model = M($this->this_table);
    $where['id'] = trim(I('id'));
    if (!$where['id']) {
      return_data("error", $this->this_table.".id.blank");
    }

    $where['id'] = trim(I('id'));
    $where['status'] = 1;
    $where['app_id'] = $this->app_id;

    $info = $model->field('id')->where($where)->find();

    if (!($info)) {
      return_data("error", "check.".$this->this_table.".empty");//blank
    } else {
      return_data("success", "check.".$this->this_table.".success", $info);
    }
  }

  //修改--只更新上传参数
  public function update()
  {
    $this->shops_close();
    //必须是商户角色或管理员
    if ($this->types != 1) {
      return_data("error", "update.".$this->this_table.".deny");
    }

    $model = M($this->this_table);
    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);

    unset($data['created_at'], $data['user_id'], $data['id'], $data['status']);

    if ($data['name'] || ($data['logo'] && !$data['name'])) {
      $data['name'] = trim($data['name']);
      if (!$data['name']) {
        return_data("error", "shop.name.blank");
      }
      //店名
      $find_shop_id = $model->where("name='{$data[name]}' and id!={$this->shop_id}")->getField("id");
      if ($find_shop_id) {
        return_data("error", $this->this_table.".name.exist");
      }
    }

    $data["updated_at"] = $this->current_time;

    $where['id'] = $this->shop_id;
    $result = $model->where($where)->save($data);
    if ($result) {
      return_data("success", "update.".$this->this_table.".success");
    } else {
      return_data("error", "update.".$this->this_table.".error");
    }
  }

  /**
   * [订单统计]
   * @return [type] [description]
   */
  public function orders_info()
  {
    $this->shops_close();
     //必须是商户角色或管理员
    if ($this->types !=1) {
      return_data("error", "order_count.shop.deny");
    }

    $today = strtotime(date("Y-m-d 00:00:00", $this->current_time));

    //订单数
    $today_end = $today + 24 * 3600;
    $where = "shop_id={$this->shop_id} and status in (2,4,5,7,9) and is_platform=0 and created_at>='$today' and created_at<'$today_end'";
    $d1['today'] = M("Orders")->where($where)->count();
    $d2['today'] = M("Orders")->where($where)->sum("total_amount");
    $d2['today'] = $d2['today'] ? $d2['today'] : 0.0;

    //七日订单--营业额
    $started_at = $today_end - 24 * 3600 * 7;
    $where = "shop_id={$this->shop_id} and status in (2,4,5,7,9) and is_platform=0 and created_at>='$started_at' and created_at<'$today_end'";
    $d1['day7'] = M("Orders")->where($where)->count();
    $d2['day7'] = M("Orders")->where($where)->sum("total_amount");
    $d2['day7'] = $d2['day7'] ? $d2['day7'] : 0.0;

    //历史订单
    $where = "status in (2,4,5,7,9) and is_platform=0 and shop_id={$this->shop_id}";
    $d1['history'] = M("Orders")->where($where)->count();
    $d2['history'] = M("Orders")->where($where)->sum("total_amount");
    $d2['history'] = $d2['history'] ? $d2['history'] : 0.0;

    //data
    $data['order_num'] = $d1;
    $data['order_amount'] = $d2;

    return_data("success", "update.order_count.success", $data);
  }

  /**
   * [店铺结算记录]
   * @return [type] [description]
   */
  public function stat()
  {
    $page = I("page", 1);
    $size = I("size", 10);

    $result = M('settlements')->where("shop_id={$this->shop_id}")
      ->order('day desc')
      ->page("{$page},{$size}")
      ->select();

    if ($result) {
      foreach ($result as $key => $value) {
        $result[$key]['day'] = format_datetime($result[$key]['day']);
        $result[$key]['status'] = $value['status'] == 2 ? '已打款' : '未打款';
      }
      return_data('success', 'shop.stat.success', $result);
    } else {
      return_data('error', 'shop.stat.error');
    }
  }
  //体现结算
  public function withdraw()
  { 
    $this->shops_close();
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    $app_info = $this->app_info;

    $shop = M('shops')->where("id={$this->shop_id}")->find();

    if ($shop) {
      if ($data['types'] == 1 && $shop['amount'] >= $app_info['withdraw_min_amount']){
        #每日提现次数限制
        $today = strtotime('today');
        $log_count = M('amount_logs')->where("created_at >= $today and shop_id = {$shop['id']} and status in (2,3)")->count();
        if ($log_count >= $app_info['withdraw_daily_times']) {
          return_data('error', 'shop.withdraw.too_many_times_today');
        }
        $withdraw_amount = $shop['amount'] > $app_info['withdraw_max_amount'] ? $app_info['withdraw_max_amount'] : $shop['amount'];
        $shop_amount = $shop['amount'] - $withdraw_amount;
        #生成提现记录
        $rate_amount = floor($withdraw_amount * (1000 - $shop['rate']) / 1000 * 100) / 100;
        $log = array(
          'total_amount' => $withdraw_amount,
          'app_id' => $this->app_id,
          'amount' => $rate_amount,
          'rate' => $shop['rate'],
          'status' => 2,
          'shop_id' => $shop['id'],
          'pay_types' => $data['pay_types'],
          'types' => 1,
          'form_id' => $data['form_id']
        );
      } elseif ($data['types'] == 2 && $shop['brokerage'] >= $app_info['withdraw_min_amount']) {

        $brokerage = $shop['brokerage'] > $app_info['withdraw_max_amount'] ? $app_info['withdraw_max_amount'] : $shop['brokerage'];

        $shop_brokerage = $shop['brokerage'] - $brokerage;

        $log = array(
          'total_amount' => $brokerage,
          'app_id' => $this->app_id,
          'amount' => $brokerage,
          'rate' => 0,
          'status' => 2,
          'shop_id' => $shop['id'],
          'pay_types' => $data['pay_types'],
          'types' => 2,
          'form_id' => $data['form_id']
        );
      } else {
        return_data('error', 'withdraw.shop.invalid');
      }

      $log['created_at'] = $this->current_time;
      $log_id = M('amount_logs')->add($log);

      if ($log_id) {
        if ($data['types'] == 1) {
          #冻结商户余额
          M('shops')->where("id={$this->shop_id}")->save(array('amount' => $shop_amount));
          #生成提醒消息
          $user = $this->check_login;
          $msg = array(
            'app_id' => $this->app_id,
            'user_id' => $this->user_id,
            'amount_log_id' => $log_id,
            'content' => "新的余额提现申请",
            'status' => 0,
            'types' => 2
          );
        } elseif ($data['types'] == 2) {
          #冻结商户余额
          M('shops')->where("id={$this->shop_id}")->save(array('brokerage' => $shop_brokerage));
          #生成提醒消息
          $user = $this->check_login;
          $msg = array(
            'app_id' => $this->app_id,
            'user_id' => $this->user_id,
            'amount_log_id' => $log_id,
            'content' => "新的返利提现申请",
            'status' => 0,
            'types' => 6
          );
        }
        $msg['created_at'] = $msg['updated_at'] = $this->current_time;
        M('messages')->add($msg);

        if ($app_info['withdraw_is_auto'] == 1 && $log['pay_types'] == 1) {
          $log = M('amount_logs')->alias('l')
                                 ->join("left join ".C("DB_PREFIX")."shops s on s.id=l.shop_id")
                                 ->join("left join ".C("DB_PREFIX")."users u on u.shop_id=s.id")
                                 ->where("l.id=$log_id and l.status=2")
                                 ->field('l.*, u.xcx_openid,s.alipay_name truename')
                                 ->find();
          $log['tran_no'] = "p".date("YmdHis", gmtime()).random(4, 1);
          $result = wxpay_to_shop($log);
          #更新记录
          if ($result['result_code'] && $result['result_code'] == 'SUCCESS') {

            $log_update = array(
              'status' => 3,
              'payed_at' => $this->current_time,
              'tran_no' => $log['tran_no'],
              'payment_no' => $result['payment_no']
            );
            M('amount_logs')->where("id=$log_id")->save($log_update);
            #更新提醒
            M('messages')->where("amount_log_id=$log_id and types in (2,6) and status<2")->save(array('status' => 2));

            send_withdraw_payed_message_to_shop($log_id);
            return_data('success', 'shop.withdraw.success');
          }
        }
        return_data('success', 'shop.withdraw_apply.success');
      }
    } else {
      return_data('error', 'withdraw.shop.invalid');
    }
  }

  public function get_logs()
  {
    $this->shops_close();
    $page_index = I("page", 1);
    $page_size = I("size", 10);
    $status = I('status', 0);

    $where = "shop_id={$this->shop_id}";

    if ($status && $status != 4) {
      $where .= " and status = $status";
    }

    //排序
    $order = "id desc";
    if ($status && $status == 4) {
      $list = M('brokerage_logs')->where($where)->page($page_index.",".$page_size)->order($order)->select();
    } else {
      $list = M('amount_logs')->where($where)->page($page_index.",".$page_size)->order($order)->select();
    }

    foreach ($list as $key => &$info) {
      $info['created_at'] = date("Y-m-d", $info['created_at']);//local_time($info['created_at']);
    }

    return_data("success", "index.amount_logs.success", $list);
  }

  public function refund_audit()
  {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    $order_id = $data['id'];
    $status = $data['status'];
    $app_info = $this->app_info;

    $where = "id={$order_id} and status=6";
    $order = M('orders')->where($where)->find();

    #生成提醒消息
    $msg = array(
      'app_id' => $this->app_id,
      'user_id' => $this->user_id,
      'order_id' => $order_id,
      'content' => "新的退款申请已通过，订单号{$order['tran_no']}",
      'status' => 0,
      'types' => 1
    );
    $msg['created_at'] = $msg['updated_at'] = $this->current_time;

    if ($order && $status==10) {
      $data = array(
        'updated_at' => $this->current_time,
        'status' => 10);

      M('orders')->where("id={$order_id}")->save($data);

      M('messages')->add($msg);

      $unbilled_amount = M("Shops")->where("id = {$this->shop_id}")->getField('unbilled_amount');
      $unbilled_amount -= $order['total_amount'];
      M("Shops")->where("id = {$this->shop_id}")->save(array("unbilled_amount" => $unbilled_amount));

      return_data('success', 'order.refund.success');
    } elseif ($order && $status == 9) {
      $data = array(
        'updated_at' => $this->current_time,
        'status' => 9,
        'refund_reject_reason' => $data['reason']);

      $result = M('orders')->where("id={$order_id}")->save($data);

      if ($result) {
        #添加后台消息
        $msg['content'] = "新的退款申请已拒绝，订单号{$order['tran_no']}";
        $msg['types'] = 3;
        M('messages')->add($msg);

        #小程序消息提醒
        $order_child = M('order_children')->where("order_id={$order['id']}")->find();
        $content =  "{$order_child['product_name']} 等商品";

        $shop = M('shops')->where("id={$this->shop_id}")->field('name,phone')->find();
        $user = M('users')->where("id={$order['user_id']}")->field('xcx_openid')->find();

        $order['xcx_openid'] = $user['xcx_openid'];
        $order['template_id'] = $app_info['refund_reject_template_id'];
        $order['form_id'] = $order['prepay_id'];

        $order['data'] = array(
          'keyword1' => array('value' => $order['tran_no'], 'color' => '#173177'),
          'keyword2' => array('value' => $content, 'color' => '#173177'),
          'keyword3' => array('value' => $data['refund_reject_reason'], 'color' => '#173177'),
          'keyword4' => array('value' => "店家：{$shop['name']}, 联系方式：{$shop['phone']}", 'color' => '#173177')
          );
        $order['page'] = "pages/orders/order?id={$order['id']}";

        $result = send_app_msg($order, $this->app_id);

        return_data('success', 'order.refund_reject.success', $result);
      } else {
        return_data('error', 'order.reject.error');
      }
    } else {
      return_data('error', 'order.reject.invalid');
    }
  }

  public function proxy_product()
  {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    $cate_id = $data['category_id'];
    if (!$cate_id) {
      return_data("error", "product.cate_id.blank");
    }

    $proxy_check = M('products')->where("pf_id={$data['id']} and shop_id={$this->shop_id} and product_cate_id={$cate_id} and status<2")->find();
    if ($proxy_check) {
      return_data("error", "product.proxy.exist");
    }
    $product = M('products')->where("id={$data['id']}")->find();

    $time = $product['limit_depot']-time();

    if($time<0 && $product['limit_depot']>0){
       return_data("error","product.time.expired");
    }
    $product['pf_id'] = $product['id'];
    $product['shop_id'] = $this->shop_id;
    $product['product_cate_id'] = $cate_id;
    $product['product_num'] = 0;
    $product['created_at'] = time();
    $product['updated_at'] = time();

    unset($product['id']);
    $product_id = M('products')->add($product);

    if ($product_id) {
      return_data("success", "product.proxy.success", $product_id);
    } else {
      return_data("error", "product.proxy.error");
    }

  }

  /*
   * 获取最新店铺信息
   */
  public function info()
  {
    $id = I('id', 0);
    $shop = M("shops")->where(array('id' => $id))->find();

    if (!$shop) {
        return_data("error", "shops.not.exists");
    } else {
        return_data("success", "shops.info.success", $shop);
    }
  }
}
